﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using GalaSoft.MvvmLight;
using System.ComponentModel;
using System.Threading;
using System.Windows.Threading;
using GalaSoft.MvvmLight.Messaging;

namespace AzureTracer.ViewModels
{
    public class SearchViewModel : ObservableObject
    {
        public const string ISSEARCHING_MESSAGE = "IsSearching";

        private const string SearchTextPropertyName = "SearchText";
        private const string SearchCommandPropertyName = "SearchCommand";

        private DispatcherTimer _timer;

        private string _searchText;

        public bool IsSearching
        {
            set { Messenger.Default.Send<bool>(value, ISSEARCHING_MESSAGE); }
        }

        public SearchViewModel()
        {
            _timer = new DispatcherTimer();
            _timer.Interval = new TimeSpan(0, 0, 0, 0, 1000);
            _timer.Tick += (sender, e) =>
                {
                    _timer.Stop();
                    SearchCommand.Execute(SearchText);
                    IsSearching = false;
                };
        }

        /// <summary>
        /// Sets and gets the SearchText property.
        /// Changes to that property's value raise the PropertyChanged event. 
        /// </summary>
        public string SearchText
        {
            get { return _searchText; }
            set
            {
                string newSearch = value.Trim();
                if (_searchText == newSearch) return;

                _searchText = newSearch;
                ExecuteSearch();

                RaisePropertyChanged(SearchTextPropertyName);
            }
        }


        private ICommand _searchCommand;

        /// <summary>
        /// Sets and gets the SearchCommand.
        /// </summary>
        public ICommand SearchCommand
        {
            get { return _searchCommand; }
            set
            {
                if (_searchCommand == value) return;

                _searchCommand = value;
                RaisePropertyChanged(SearchCommandPropertyName);
            }
        }

        public void ResetText()
        {
            SearchText = string.Empty;
        }

        private void ExecuteSearch()
        {
            if (null != SearchCommand && SearchCommand.CanExecute(null))
            {
                IsSearching = true;
                if (_timer.IsEnabled)
                    _timer.Stop();
                _timer.Start();
            }
        }
    }
}
